/*
 * @Author: your name
 * @Date: 2021-04-07 15:47:47
 * @LastEditTime: 2021-04-27 14:22:40
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \dolphin-data-center-front-end\src\utils\util.js
 */
import enquireJs from 'enquire.js'
import { getOSSConfig } from '@/services/os'

export function isDef(v) {
  return v !== undefined && v !== null
}

/**
 * Remove an item from an array.
 */
export function remove(arr, item) {
  if (arr.length) {
    const index = arr.indexOf(item)
    if (index > -1) {
      return arr.splice(index, 1)
    }
  }
}

export function isRegExp(v) {
  return _toString.call(v) === '[object RegExp]'
}

export function enquireScreen(call) {
  const handler = {
    match: function() {
      call && call(true)
    },
    unmatch: function() {
      call && call(false)
    },
  }
  enquireJs.register('only screen and (max-width: 767.99px)', handler)
}
/**
 * @description:时间格式转换
 * @param {
 * time：{string} 时间戳，
 * type：{number} 0：年月日，1：时分秒，2：年月日-时分秒
 * }
 * @return {*}
 */
export function transferDate(time, type) {
  var date = new Date(time + 8 * 3600 * 1000)
  //年月日 时分秒(0, 19)  年月日(0,10)  时分秒(11,8)
  let config = [
    [0, 11, 0],
    [10, 8, 19],
  ]
  return date
    .toJSON()
    .substr(config[0][type], config[1][type])
    .replace('T', ' ')
    .replace(/-/g, '-')
}
// 时间戳转时间格式
export function time(time = +new Date()) {
  var date = new Date(time + 8 * 3600 * 1000) // 增加8小时
  return date
    .toJSON()
    .substr(0, 19)
    .replace('T', ' ')
}
export var storage = {
  //存储
  set(key, value) {
    localStorage.setItem(key, JSON.stringify(value))
  },
  //取出数据
  get(key) {
    return JSON.parse(localStorage.getItem(key))
  },
  // 删除数据
  remove(key) {
    localStorage.removeItem(key)
  },
}
// 上传到阿里云
export function upLoadAliyun(param) {
  // 类型兼容
  let data = param.name ? param.name : param.file.name
  // console.log('param', param, data)
  // 根据资源后缀判断type类型
  // 1.图片 2.视频 3.合同文件 4.音频
  let typeFormat = {
    1: ['jpg', 'png', 'jpeg', 'gif', 'heic'],
    2: ['mp4', 'avi'],
    3: ['pdf'],
    4: ['amr', 'wav', 'aac', 'mp3', 'm4a'],
    5: ['xls', 'xlsx'],
  }
  let type = null
  for (let key in typeFormat) {
    typeFormat[key].includes(data.split('.')[data.split('.').length - 1]) &&
      (type = key)
  }
  // console.log('type', type)
  return new Promise((resolve, reject) => {
    getOSSConfig({
      type,
    }).then((res) => {
      let {
        bucket,
        accessEndpoint,
        accessKeyId,
        accessKeySecret,
        region,
        stsToken,
        targetDir,
      } = res.data.data.oss

      var client = new window.OSS({
        bucket,
        accessKeyId,
        accessKeySecret,
        region,
        stsToken,
      })
      // 文件重命名
      let reName = `${new Date().getTime()}-${
        Math.random()
          .toString()
          .split('.')[1]
      }.${data.split('.')[data.split('.').length - 1]}`
      client
        .multipartUpload(`${targetDir}/${reName}`, param.raw || param.file)
        .then((result) => {
          result.filePath = `${accessEndpoint}${targetDir}/${reName}`
          // console.log('result.filePath', result.filePath)
          resolve(result)
        })
        .catch((err) => {
          reject(err)
        })
    })
  })
}
export function getAge(strAge) {
  var birArr = strAge.split('-')
  var birYear = birArr[0]
  var birMonth = birArr[1]
  var birDay = birArr[2]

  d = new Date()
  var nowYear = d.getFullYear()
  var nowMonth = d.getMonth() + 1 //记得加1
  var nowDay = d.getDate()
  var returnAge

  if (birArr == null) {
    return false
  }
  var d = new Date(birYear, birMonth - 1, birDay)
  if (
    d.getFullYear() == birYear &&
    d.getMonth() + 1 == birMonth &&
    d.getDate() == birDay
  ) {
    if (nowYear == birYear) {
      returnAge = 0 //
    } else {
      var ageDiff = nowYear - birYear //
      if (ageDiff > 0) {
        if (nowMonth == birMonth) {
          var dayDiff = nowDay - birDay //
          if (dayDiff < 0) {
            returnAge = ageDiff - 1
          } else {
            returnAge = ageDiff
          }
        } else {
          var monthDiff = nowMonth - birMonth //
          if (monthDiff < 0) {
            returnAge = ageDiff - 1
          } else {
            returnAge = ageDiff
          }
        }
      } else {
        return '出生日期晚于今天，数据有误' //返回-1 表示出生日期输入错误 晚于今天
      }
    }
    return returnAge
  } else {
    return '输入的日期格式错误！'
  }
}
const _toString = Object.prototype.toString
